package cn.itcast.bos.web.action.base;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;


import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;
import javassist.compiler.ast.NewExpr;

@Controller
@Actions
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {

	private Standard standard = new Standard(); 	
	@Autowired
	private StandardService service;
	
	private Integer page;
	private Integer rows;
	
	
	
	public void setPage(Integer page) {
		this.page = page;
	}
	
	public void setRows(Integer rows) {
		this.rows = rows;
	}
	@Override
	public Standard getModel() {
		return standard;
	}
	@Action(value="standard_save",results={@Result(location="./pages/base/standard.html",type="redirect")})
	public String save(){
		service.save(standard);

		return SUCCESS;
	}
	
	@Action(value="standard_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows);
		Page<Standard> page = service.pageQuery(pageable);
		Map<String , Object> p = new HashMap<String,Object>();
		p.put("total", page.getTotalElements());
		p.put("rows", page.getContent());
		
		ActionContext.getContext().getValueStack().push(p);
		return SUCCESS;	
	}
	@Action(value="standard_findAll",results={@Result(name="success",type="json")})
	public String findAll(){
		List<Standard> list = service.findAll();
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
		
	}
	
	@Action(value="getJson")
	public String getJson() throws IOException{
		String callback = ServletActionContext.getRequest().getParameter("callback");
		ServletActionContext.getResponse().getWriter().write(callback+"(1)");
		return null;
		
	}
}
